module.exports = class extends think.Controller {
  async __before() {
    // 登录验证
    const is_login = await this.islogin();
    if (!is_login) {
      return this.redirect('/admin/public/signin');
    }
    this.is_login = is_login;
    this.user = await this.session('userInfo');
    this.assign('userinfo', this.user);
    this.roleid = await this.model('auth_user_role').where({user_id: this.user.uid}).getField('role_id', true); // 获取用户角色
    this.is_admin = await this.is_admin();
    // 后台菜单
    // this.adminmenu = await this.model('kms/menu').getallmenu(this.user.uid, this.is_admin);
    this.adminmenu = {};
    const url = `${this.ctx.controller}/${this.ctx.action}`;
    think.logger.debug(url)
    think.logger.debug('123123')
    if (!this.is_admin) {
      const auth = this.service('kms/rbac', this.user.uid);
      const res = await auth.check(url);
      if (!res) {
        const error = this.controller('kms/error');
        return error.noAction('未授权访问!');
      }
    }
  }


  async islogin() {
    const user = await this.session('userInfo');
    const res = think.isEmpty(user) ? false : user.uid;
    return res;
  }

  /**
     * 检查当前用户是否为管理员
     * @param uid
     * @returns {*|boolean}
     */
  async is_admin(uid) {
    uid = uid || null;
    uid = think.isEmpty(uid) ? await this.islogin() : uid;
    return uid && (in_array(parseInt(uid), this.config('user_administrator')));
  }
};
